#include "Input.h"


CInput::CInput(HINSTANCE hInstance, HWND hWnd)
{
	this->hInstance_	= hInstance;
	this->hWnd_			= hWnd;
	HRESULT hr = DirectInput8Create( hInstance_, DIRECTINPUT_VERSION, IID_IDirectInput8, (VOID**)&this->dInput_, NULL );
	if (hr!=DI_OK) 
		return;
	hr = dInput_->CreateDevice(GUID_SysKeyboard, &this->Keyboard_, NULL); 
	if (hr!=DI_OK) 
		return;
	hr = Keyboard_->SetDataFormat(&c_dfDIKeyboard);
	if (hr!=DI_OK) 
		return;
	hr = Keyboard_->SetCooperativeLevel(hWnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE); 
	if (hr!=DI_OK)
		return;
	DIPROPDWORD dipdw;

	dipdw.diph.dwSize       = sizeof(DIPROPDWORD);
	dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
	dipdw.diph.dwObj        = 0;
	dipdw.diph.dwHow        = DIPH_DEVICE;
	dipdw.dwData            = KEYBOARD_BUFFER_SIZE;
	hr = Keyboard_->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph );
	if (hr!=DI_OK) 
		return;

	hr = Keyboard_->Acquire(); 
	if (hr!=DI_OK) 
		return;

}


CInput::~CInput(void)
{
	if( Keyboard_ )  
	{
		Keyboard_->Unacquire();
		Keyboard_->Release();
	}

	if (dInput_) dInput_->Release();
}

void CInput::Update()
{
	// Collect all key states first
	memcpy(PreKeyStates_,KeyStates_,sizeof(KeyStates_));
	Keyboard_->GetDeviceState( sizeof(KeyStates_), KeyStates_);
	//ProcessingState();

	//// Collect all buffered events
	//DWORD dwElements = KEYBOARD_BUFFER_SIZE;
	//HRESULT hr = Keyboard_->GetDeviceData( sizeof(DIDEVICEOBJECTDATA), _KeyEvents, &dwElements, 0 );

	//// Scan through all data, check if the key is pressed or released
	//for( DWORD i = 0; i < dwElements; i++ ) 
	//{
	//	int KeyCode = _KeyEvents[i].dwOfs;
	//	int KeyState = _KeyEvents[i].dwData;
	//	if ((KeyState & 0x80) > 0)
	//		pressedKey_[KeyCode] = true;
	//	else
	//		pressedKey_[KeyCode] = false;
	//}
}


bool CInput::KeyDown(int KeyCode)
{
	return ISKEYDOWN(KeyStates_[KeyCode]) > 0;
}

bool CInput::KeyUp(int KeyCode)
{
	return ISKEYDOWN(KeyStates_[KeyCode]) == 0;
}

bool CInput::KeyPress(int KeyCode)
{
	if(ISKEYDOWN(PreKeyStates_[KeyCode]) > 0)
		return ISKEYDOWN(KeyStates_[KeyCode]) > 0;
	return false;
}

bool CInput::KeyRelease(int KeyCode)
{
	if(ISKEYDOWN(KeyStates_[KeyCode]) > 0)
		return KeyUp(PreKeyStates_[KeyCode]);
	return false;
}